package com.supermap.dialogs;

import com.supermap.consts.AttrConsts;
import com.supermap.data.FieldInfo;
import com.supermap.data.FieldInfos;
import com.supermap.dialogs.advance.CJDialog;

import javax.swing.*;
import java.awt.*;

public class NetworkFieldsSettingDialog extends CJDialog {
    private JPanel mainPanel;

    private FieldInfos fieldInfos;
    private String[] selectedFieldNames;

    public NetworkFieldsSettingDialog(Frame owner, String title, boolean modal, FieldInfos fieldInfos) {
        super(owner, title, modal, 300, 400, new Object[]{fieldInfos});
    }

    @Override
    protected void initializeArgs(Object[] args) {
        this.fieldInfos = (FieldInfos) args[0];
    }

    @Override
    protected void initializeCore() {
        int fieldInfosCount = fieldInfos.getCount();
        mainPanel = new JPanel();
        mainPanel.setLayout(new GridLayout(fieldInfosCount, 1));

        for (int i = 0; i < fieldInfosCount; i++) {
            FieldInfo fieldInfo = fieldInfos.get(i);
            JCheckBox fieldInfoCbx = new JCheckBox(fieldInfo.getName());
            mainPanel.add(fieldInfoCbx);
        }

        JScrollPane mainScrollPane = new JScrollPane(mainPanel);
        mainScrollPane.setHorizontalScrollBarPolicy(JScrollPane.HORIZONTAL_SCROLLBAR_AS_NEEDED);
        mainScrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);
        add(mainScrollPane, BorderLayout.CENTER);
    }

    @Override
    protected void doConfirmCore() {
        setVisible(false);
        Component[] components = mainPanel.getComponents();
        if (components != null && components.length > 0) {
            StringBuilder stringBuilder = new StringBuilder();
            for (Component component : components) {
                if (component instanceof JCheckBox) {
                    JCheckBox fieldInfoCbx = (JCheckBox) component;
                    if (fieldInfoCbx.isSelected()) {
                        stringBuilder.append(fieldInfoCbx.getText());
                        stringBuilder.append(AttrConsts.COMMA);
                    }
                }
            }
            selectedFieldNames = stringBuilder.substring(0, stringBuilder.length() - 1).split(AttrConsts.COMMA);
        }
    }

    public String[] getSelectedFieldNames() {
        return selectedFieldNames;
    }
}
